#include "Serveur.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* fork */

int initServeur(int port, int backlog)
{
	int socketFd;
	struct sockaddr_in localAddr;
	
	/*	Creation de la socket
		AF_INET : socket internet / SOCK_STREAM : TCP 
	*/
	socketFd = socket( AF_INET, SOCK_STREAM, 0 );
	
	if( socketFd > 0 )
	{
		/*	Liaison de la socket a un point de communication (adresse + port) */
		localAddr.sin_family = AF_INET;
		localAddr.sin_addr.s_addr = htonl( INADDR_ANY );
		localAddr.sin_port = htons(port);
		if( bind( socketFd, (struct sockaddr *)& localAddr, sizeof( localAddr ) ) == -1 )
		{
			perror("bind");
			return -1;
		}
		
		/*	Attente des connexions */
		if( listen(socketFd, backlog) == -1 )
		{
			perror("listen");
			return -1;
		}
		
		return socketFd;
	}
	
	return -1;
}

void serveurLoop(int socket, void (*callback)(int))
{
	for(;;)
	{
		int socketClient;
		int pid;
		
		/* accepte une connexion cliente */
		socketClient = accept(socket, NULL, NULL);
		
		if( socketClient > 0 )
		{
			pid = fork();
			switch(pid)
			{
				/* erreur */
				case -1:
					perror("fork");
					break;
				/* code du fils */
				case 0:
					close(socket);
					callback(socketClient);
					close(socketClient);
					return;
				default:
					close(socketClient);
					break;
			}
		}
		else
		{
			close(socketClient);
			perror("accept");
			exit(1);
		}
	}
}
